<template>
  <RenderTableColumn v-bind="column" />
</template>

<script setup lang="tsx">
import { filterEnum, formatValue, handleProp, handleRowAccordingToProp } from '@/utils';
import { inject, ref, useSlots } from 'vue';
import type {ColumnProps, RenderScope, HeaderRenderScope, tagStyleProps} from '@/components/ProTable/interface';

defineOptions({
  name: 'TableColumn'
});

defineProps<{ column: ColumnProps }>();

const slots = useSlots();

const enumMap = inject('enumMap', ref(new Map()));

// 渲染表格数据
const renderCellData = (item: ColumnProps, scope: RenderScope<any>) => {
  //handleRowAccordingToProp 获得当前单元格的值
  // enumMap.value.get(item.prop) 对应成员的data
  return enumMap.value.get(item.prop) && item.isFilterEnum
    ? filterEnum(handleRowAccordingToProp(scope.row, item.prop!), enumMap.value.get(item.prop), item.fieldNames)
    : formatValue(handleRowAccordingToProp(scope.row, item.prop!));
};

// 获取 tag 类型
const getTagType = (item: ColumnProps, scope: RenderScope<any>) => {
  return (
    filterEnum(handleRowAccordingToProp(scope.row, item.prop!), enumMap.value.get(item.prop), item.fieldNames, 'tag') || 'primary'
  );
};

function createTagStyle<T extends tagStyleProps>(style: T): T {
  return style;
}

let defaultColor = createTagStyle({
  backgroundColor: '',
  opacity: 1,
  borderRadius: '4px',
  fontSize: '15px',
  borderColor: '',
  fontWeight: 'no',
  color: '',
  totalColor: ''
});

// 去除透明度
const updateColor = (colorValue: string | undefined) => {
  if (colorValue) {
    let parts = colorValue.toString().split(',');
    if (parts.length > 3) {
      return `rgb(${parts[0].slice(5)}, ${parts[1]}, ${parts[2]})`;
    }
  }
  return colorValue;
};

const RenderTableColumn = (item: ColumnProps) => {
  return (
    <>
      {item.isShow && (
        <el-table-column
          {...item}
          align={item.align ?? 'center'}
          showOverflowTooltip={item.showOverflowTooltip ?? item.prop !== 'operation'}
        >
          {{
            default: (scope: RenderScope<any>) => {
              //存在优先级
              if (item._children) return item._children.map(child => RenderTableColumn(child));
              if (item.render) return item.render(scope);
              if (slots[handleProp(item.prop!)]) return slots[handleProp(item.prop!)]!(scope);
              if (item.tag) {
                //{renderCellData(item, scope)} 为文本处理方法
                let defalutColor = { ...defaultColor };

                // type
                if (item?.tagStyleProps) {
                  Object.assign(defalutColor, item.tagStyleProps);
                }

                // 移除空值或无效值的成员
                Object.keys(defalutColor).forEach((key) => {
                  let value = defalutColor[key as keyof typeof defalutColor];

                  if (value === '' || (key === 'fontWeight' && value !== 'bold')) {
                    delete defalutColor[key as keyof typeof defalutColor];
                  }
                });

                let colorName = '';
                let totalColor = '';
                //处理对应枚举
                if (item.tagStyleProps) {
                  let datas = enumMap.value.get(item.prop)
                  let cellValue = handleRowAccordingToProp(scope.row, item.prop!);
                  //这里item如果加上限制会找不到对象
                  const target = datas.find((item) => item.detailValue === cellValue);
                  colorName =target?.codeName;
                  totalColor =target?.detailValue || 0;
                }
                // 处理 totalColor
                if (totalColor) {
                  defalutColor = {
                    ...defalutColor,
                    totalColor: totalColor,
                    backgroundColor: totalColor,
                    borderColor: totalColor,
                    color: totalColor,
                  };
                }

                //去除边框颜色和字体颜色的透明度设置
                const { borderColor,color } = defalutColor;
                defalutColor['color'] = updateColor(color) ||'';
                defalutColor['borderColor'] = updateColor(borderColor) ||'';
                delete defalutColor['totalColor' as keyof typeof defalutColor];


                return <el-tag type={getTagType(item, scope)}
                               style={defalutColor}
                >{colorName ? colorName: renderCellData(item, scope)}</el-tag>;
              }
              return renderCellData(item, scope);
            },
            header: (scope: HeaderRenderScope<any>) => {
              if (item.headerRender) return item.headerRender(scope);
              if (slots[`${handleProp(item.prop!)}Header`]) return slots[`${handleProp(item.prop!)}Header`]!(scope);
              return item.label;
            }
          }}
        </el-table-column>
      )}
    </>
  );
};
</script>
